﻿using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;

namespace WebFile.Models
{

    public static class HtmlHelperExtensions
    {
        public static IHtmlContent Pager(this IHtmlHelper html, int totalItems, int currentPage, int pageSize, Func<int, string> pageUrl, int maxPagesToShow = 5)
        {
            int totalPages = (int)Math.Ceiling((double)totalItems / pageSize);
            var sb = new StringBuilder();

            if (currentPage > 1)
            {
                sb.Append($"<a class='layui-laypage-prev' href='{pageUrl(currentPage - 1)}'>&lt;</a>");
            }

            int startPage = Math.Max(currentPage - (maxPagesToShow / 2), 1);
            int endPage = Math.Min(startPage + maxPagesToShow - 1, totalPages);

            for (int i = startPage; i <= endPage; i++)
            {
                if (i == currentPage)
                {
                    sb.Append($"<span class='layui-laypage-curr'><em class='layui-laypage-em'></em><em>{i}</em></span>");
                }
                else
                {
                    sb.Append($"<a href='{pageUrl(i)}'>{i}</a>");
                }
            }

            if (currentPage < totalPages)
            {
                sb.Append($"<a class='layui-laypage-next' href='{pageUrl(currentPage + 1)}'>&gt;</a>");
            }

            return new HtmlString(sb.ToString());
        }
    }
}
